package leetcode.d24;

//stones = [2,7,4,1,8,1]
public class Solution {
    public static int lastStoneWeightII(int[] stones) {
        int total = 0;
        for (int stone : stones) {
            total += stone;
        }
        int half = total / 2;
        int[][] d = new int[stones.length][half + 1];
        //初始化
        for (int j = 0; j <= half; j++) {
            if (j >= stones[0]) {
                d[0][j] = stones[0];
            } else {
                d[0][j] = 0;
            }
        }
        for (int j = 1; j <= half; j++) {
            for (int i = 1; i < stones.length; i++) {
                if (j >= stones[i]) {
                    d[i][j] = Integer.max(d[i - 1][j], d[i - 1][j - stones[i]] + stones[i]);
                } else {
                    d[i][j] = d[i - 1][j];
                }
            }
        }

        int i = total - d[stones.length - 1][half];
        return i - d[stones.length - 1][half];

    }

    public static void main(String[] args) {
        int[] nums = {2, 7, 4, 1, 8, 1};
        int[] a = {31, 26, 33, 21, 40};
//        int[] nums = {1, 2};
        int i = lastStoneWeightII(nums);
        System.out.println(i);
    }
}
